A good answer might be:

Registering a listener object establishes a channel of communication between the GUI object and the listener.

Registering the Listener

The container (a ButtonDemo2 object) can be registered as a listener for any of the components it contains. When a ButtonDemo2 object is constructed we will register it as an ActionListener for its own button.

public class ButtonDemo2 extends JFrame implements ActionListener
{
  JButton bChange;
  
  public ButtonDemo2() 
  {
    // choose the layout manager 
    getContentPane().setLayout( new FlowLayout() );
    bChange = new JButton("Click Me!"); 

    // register the buttonDemo object 
    // as the listener for the JButton.

    bChange.addActionListener( this ); 
    
    getContentPane().add( bChange ); 
  }

  public void actionPerformed( ActionEvent evt)
  {
      . . . . .
  }

  public static void main ( String[] args )
  {
    ButtonDemo2 frm = new ButtonDemo2();
      . . . . .
  }
}

Examine the statement:

bChange.addActionListener( this );

This statement is executed when a ButtonDemo2 object is constructed.

  1. bChange refers to the button.
  2. The button has a method that that registers a listener for its events: addActionListener()
  3. The listener is the ButtonDemo2 object.
    • The word this means the object being constructed.
  4. The statement tells the button (bChange) to run its method (addActionListener()) to register the frame (this) as a listener for button clicks.
  5. Now the frame is listening for actionEvents from the button it contains.
  6. Events will be sent to the actionPerformed() method

You might think that the ButtonDemo2 frame should automatically be registered as the listener for all of the GUI components it contains. But this would eliminate the flexibility that is needed for more complicated GUI applications.

QUESTION 12:

You want the program to do something when the button is clicked. Where should the code to "do something" go?